package org.nobody.mallb2c.mallseckill.config;

import com.alibaba.csp.sentinel.adapter.servlet.callback.UrlBlockHandler;
import com.alibaba.csp.sentinel.adapter.servlet.callback.WebCallbackManager;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.fastjson.JSON;
import org.nobody.common.exception.ResultCodeEnum;
import org.nobody.common.utils.R;
import org.springframework.context.annotation.Configuration;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author 3489309323@qq.com
 * @create 2020-09-29-15:22
 */
@Configuration
public class SeckillSentinelConfig {
  public SeckillSentinelConfig(){
    WebCallbackManager.setUrlBlockHandler(new UrlBlockHandler() {
      @Override
      public void blocked(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, BlockException e) throws IOException {
        R error = R.error(ResultCodeEnum.TOO_MANY_REQUEST.getCode(), ResultCodeEnum.TOO_MANY_REQUEST.getMsg());
        httpServletResponse.setCharacterEncoding("UTF-8");
        httpServletResponse.setContentType("application/json");
        httpServletResponse.getWriter().write(JSON.toJSONString(error));
      }
    });
  }
}
